/*
   Copyright 2009 Marcin Szczepanski, webqem (marcins@gmail.com)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

function NapkinState(stateString, owner) {
    this.stateParts = stateString.split("|");
    this.stateString = stateString;
    this.isUndone = false;
    this.owner = owner;
}
    
NapkinState.prototype.getStateTime = function() {
    if(this.stateString.charAt(0) != "v") return 0;
    return Number(this.stateParts[1]);
}

NapkinState.prototype.drawState = function(canvas) {
    var stroking = false;
    var ctx = canvas.getContext("2d");
    var l = this.stateParts.length;
    for(var i = 0;i < l; i++) {
        var part = this.stateParts[i];
        var command = part[0];
        var params = part.substr(1).split(",");
        switch(part[0]) {
            case "m":
                //console.log("Moving to:" + params[0] + "," + params[1]);
                ctx.beginPath();
                ctx.moveTo(params[0], params[1]);
                stroking = true;
                break;
            case "l":
                //console.log("Drawing to:" + params[0] + "," + params[1]);
                ctx.lineTo(params[0], params[1]);
                break;
            case "s":
                ctx.lineWidth = params[0];
                ctx.strokeStyle = this.colourToRGB(params[1]);
                break;
            case "c":
                console.log("Clearing canvas");
                canvas.width = canvas.width;
                break;
            case "u":
                break;
        }
    }
    if(stroking) {
        ctx.stroke();
    }
}

NapkinState.prototype.colourToRGB = function(colour) {
  var r = (colour & 0xff0000) >> 16;
  var g = (colour & 0x00ff00) >> 8;
  var b = (colour & 0x0000ff);
  
  return "rgb(" + r + "," + g + "," + b + ")"; 
}

NapkinState.prototype.containsCommandType = function(type) {
  var l = this.stateParts.length;
  for(var i = 0;i < l; i++) {
      var part = this.stateParts[i];
      var command = part[0]; 
      if(command == type) {
        return true;
      }
  }
  return false;
}

function sortByStateTime(a,b) {
   // console.log("compare " + a + " " + b);
    
    var aStateString = wave.getState().get(a);
    var bStateString = wave.getState().get(b);
    
    var aState = new NapkinState(aStateString, "");
    var bState = new NapkinState(bStateString, "");
    
    var aTime = aState.getStateTime();
    var bTime = bState.getStateTime();
    
   // console.log(aTime + " " + bTime);
    
    if(aTime < bTime) {
        return -1;
    } else if(aTime > bTime) {
        return 1;
    } else {
        return 0;
    }
}

var states = [];

function onStateChange() {
	console.log("napkinCanvasViewer::onStateChange");
    var keys = wave.getState().getKeys();
    var state = null;
    
    states = [];
    
    keys.sort(sortByStateTime);
    
    for(var i = 0; i < keys.length; i++) {
      var key = keys[i];
      var isPathKey = (key.indexOf("path-") > -1);
      if(isPathKey) {
        var value = wave.getState().get(key);
        var owner = key.substr(5, key.lastIndexOf("-") - 5);
      	console.log("owner: " + owner + " value:" + value);
      	state = new NapkinState(value, owner);
    
        states.push(state);
      }
    }
    
    applyUndos();
    drawStates();    
}

function applyUndos() {
  // apply undo
  if(states.length > 1) {
    for(var idxState = 1; idxState < states.length; idxState++) {
  	  state = states[idxState];
      if(state.containsCommandType("u")) {
  	    for(var idxUndo = idxState - 1; idxUndo >= 0; idxUndo--) {
  	      var stateTest = states[idxUndo];
            // undo states that aren't yet undone and belong to 
            // the person whose undo it is
            if(!stateTest.isUndone && 
                stateTest.owner == state.owner) {
                  stateTest.isUndone = true;
                  break;
            }
        }
      }    
    }
  }
}

function drawStates()
{
  for(var i = 0; i < states.length; i++) {
    var state = states[i];
    if(!state.isUndone) {
  	  state.drawState(napkinViewerCanvas);        
    }
  }
}

function setupCanvasViewer() {
  if (napkinViewerCanvas.getContext){
    var container = document.getElementById("NapkinGadget-container");
    napkinViewerCanvas.width = document.body.clientWidth;
    napkinViewerCanvas.height = document.body.clientHeight;
    console.log(napkinViewerCanvas.width + "," + napkinViewerCanvas.height);
	  wave.setStateCallback(onStateChange);
  }
}
